Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

165
Visualizações
How do i create a function, which takes one parameter - a number, and returns the sum of numbers from 1 -> number - without creating an infinite loop?

How do i create a function, which takes one parameter - a number, and returns the sum of numbers from 1 -> number - without creating an infinite loop?

Example:
function(100)
= 5050

Ive come as far as creating a finite for loop as so:

let sum = 0
for (let i = 1; i <= 100; i++) {
    sum = sum + i;

//thanks in advance

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Well, it looks like you've got the basic premise sussed out for 1 to 100 - you're cycling through to the value and summing up. To put it into a bit of a nicer format:

const n = 100;

console.log(GetSumTo(n))

function GetSumTo(x) {
    var sum = 0;
    for (var i = 1; i <= x; i++) {
        sum = sum + i;
    }
    return sum;
}

Another option would be do it recursively:

const n = 100;

console.log(RecursiveSum(n, 0));

function RecursiveSum(val, sum) {
    if (val > 1) {
        sum = val + RecursiveSum(val - 1, sum);
    }
    else {
        sum = val;
    }
    return sum;
}

However, these can be time consuming when dealing with large values. Using a fancy bit of maths (explained here better than I can explain it: https://math.stackexchange.com/questions/1100897/sum-of-consecutive-numbers), we can find that the sum of consecutive numbers can be calculated with an easier formula: (n(n + 1))/2

Meaning we can just write a function to do that and save execution time:

const n = 100;

console.log(QuickSum(n));

function QuickSum(n) {
    var sum = n + 1;
    sum = sum * n;
    sum = sum / 2; //You could shrink the calculation to sum = (n * (n + 1)) / 2 I just did it over a few lines for readability
    return sum;
};

None of these options result in an infinite loop.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda